import { NextRequest, NextResponse } from "next/server";
import { SqliteDatabase } from "@/lib/sqlite-database";

export async function GET(request: NextRequest) {
  try {
    const database = new SqliteDatabase();
    
    // 获取所有设备
    const allDevices = database.getAllDevices();
    
    // 按位置表类型分组统计（兼容多种格式）
    const c4Devices = allDevices.filter(d => 
      d.position_table_id === "表 C.4" || 
      d.position_table_id === "表C.4" || 
      d.position_table_id === "? C.4"
    );
    const c6Devices = allDevices.filter(d => 
      d.position_table_id === "表 C.6" || 
      d.position_table_id === "表C.6"
    );
    const otherDevices = allDevices.filter(d => 
      d.position_table_id !== "表 C.4" && d.position_table_id !== "表C.4" && d.position_table_id !== "? C.4" &&
      d.position_table_id !== "表 C.6" && d.position_table_id !== "表C.6"
    );
    
    console.log(`C4设备数量: ${c4Devices.length}`);
    console.log(`C6设备数量: ${c6Devices.length}`);
    console.log(`其他设备数量: ${otherDevices.length}`);
    
    // 调试：查看position_table_id的所有唯一值
    const positionTableIds = [...new Set(allDevices.map(d => d.position_table_id).filter(Boolean))];
    console.log('所有位置表ID：', positionTableIds);
    
    // 定义标准字段数量
    const C4_FIELDS = 10;
    const C6_FIELDS = 12;
    
    // 详细分析每个设备的位置参数
    const deviceAnalysis = [];
    let totalExpectedRows = 0;
    let totalActualRows = 0;
    
    // 分析C4设备
    for (const device of c4Devices) {
      const positionParams = database.getPositionParameters(device.id!);
      const expectedRows = C4_FIELDS;
      const actualRows = positionParams.length;
      
      totalExpectedRows += expectedRows;
      totalActualRows += actualRows;
      
      deviceAnalysis.push({
        id: device.id,
        device_id: device.device_id,
        name: device.name,
        specialty: device.specialty,
        table_type: "C.4",
        expected_params: expectedRows,
        actual_params: actualRows,
        missing_params: expectedRows - actualRows,
        is_complete: actualRows === expectedRows
      });
    }
    
    // 分析C6设备
    for (const device of c6Devices) {
      const positionParams = database.getPositionParameters(device.id!);
      const expectedRows = C6_FIELDS;
      const actualRows = positionParams.length;
      
      totalExpectedRows += expectedRows;
      totalActualRows += actualRows;
      
      deviceAnalysis.push({
        id: device.id,
        device_id: device.device_id,
        name: device.name,
        specialty: device.specialty,
        table_type: "C.6",
        expected_params: expectedRows,
        actual_params: actualRows,
        missing_params: expectedRows - actualRows,
        is_complete: actualRows === expectedRows
      });
    }
    
    // 找出有问题的设备
    const incompleteDevices = deviceAnalysis.filter(d => !d.is_complete);
    const missingDevices = deviceAnalysis.filter(d => d.actual_params === 0);
    const partialDevices = deviceAnalysis.filter(d => d.actual_params > 0 && d.actual_params < d.expected_params);
    
    // 计算缺失的参数总数
    const totalMissingParams = deviceAnalysis.reduce((sum, d) => sum + d.missing_params, 0);
    
    // 统计摘要
    const summary = {
      deviceCounts: {
        c4: c4Devices.length,
        c6: c6Devices.length,
        other: otherDevices.length,
        total: allDevices.length
      },
      expectedRows: {
        c4: c4Devices.length * C4_FIELDS,
        c6: c6Devices.length * C6_FIELDS,
        total: totalExpectedRows
      },
      actualRows: {
        total: totalActualRows
      },
      gaps: {
        totalMissing: totalMissingParams,
        incompleteDevices: incompleteDevices.length,
        missingDevices: missingDevices.length,
        partialDevices: partialDevices.length
      }
    };
    
    // 分析可能的原因
    const analysis = {
      calculated_expected: c4Devices.length * C4_FIELDS + c6Devices.length * C6_FIELDS,
      database_actual: totalActualRows,
      gap: (c4Devices.length * C4_FIELDS + c6Devices.length * C6_FIELDS) - totalActualRows,
      recently_cleaned: "刚清理了设备119-130的120个位置参数",
      before_cleanup_estimate: totalActualRows + 120 // 估算清理前的数据量
    };
    
    return NextResponse.json({
      success: true,
      message: "位置参数数据缺口分析完成",
      summary,
      analysis,
      problemDevices: {
        incomplete: incompleteDevices.slice(0, 10), // 只显示前10个问题设备
        missing: missingDevices.slice(0, 10),
        partial: partialDevices.slice(0, 10)
      },
      recommendations: [
        `期望总行数: ${summary.expectedRows.total} (C4: ${summary.expectedRows.c4} + C6: ${summary.expectedRows.c6})`,
        `实际总行数: ${summary.actualRows.total}`,
        `缺失行数: ${summary.gaps.totalMissing}`,
        `有问题的设备: ${incompleteDevices.length} 个`,
        `完全缺失参数的设备: ${missingDevices.length} 个`,
        `参数不完整的设备: ${partialDevices.length} 个`,
        analysis.before_cleanup_estimate > 1400 ? `清理前估计有 ${analysis.before_cleanup_estimate} 行，接近期望值` : "数据可能在其他环节丢失"
      ]
    });
    
  } catch (error) {
    console.error("分析位置数据缺口时出错:", error);
    return NextResponse.json(
      { 
        success: false, 
        message: "分析位置数据缺口过程中发生错误",
        error: error instanceof Error ? error.message : "未知错误"
      },
      { status: 500 }
    );
  }
} 